﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TA.JSON;
using TA.Turbo.Controls;
using TA.DotNetUtils;

namespace TA.Turbo
{
	/// <summary>
	/// Contains extensions methods for <see cref="TA.JSON.JsonReader"/> class.
	/// </summary>
	public static class _JsonReaderExtensions
	{
		/// <summary>
		/// Deserializes an object using the specified <see cref="PropertyPair"/> collection.
		/// </summary>
		/// <param name="This"></param>
		/// <param name="obj"></param>
		/// <param name="properties"></param>
		public static void Deserialize(this JsonReader This, object obj, IEnumerable<PropertyPair> properties)
		{
			This.Read(JsonToken.StartObject);

			while (This.TokenType != JsonToken.EndObject)
			{
				This.Expect(JsonToken.PropertyName);
				string prName = (string)This.Value;
				This.Read();

				foreach (PropertyPair pp in properties)
				{
					if (string.Equals(pp.JSONProperty, prName))
					{
						if(pp.Children.Count > 0)
						{
							object container = obj.Eval(pp.ObjectProperty);
							This.Deserialize(container, pp.Children);
						}
						else
						{
							obj.Store(pp.ObjectProperty, This.Value);
						}
						break;
					}
				}
				This.Read();
			}

			This.Read(JsonToken.EndObject);
		}
	}
}
